package com.nari.ysphd.ui;

import android.content.Context;
import android.net.TrafficStats;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;

import com.jeremyfeinstein.event.HDMsgEvent;
import com.jeremyfeinstein.gson.bean.LoginBean;
import com.jeremyfeinstein.gson.bean.QueryDeviceBean;
import com.jeremyfeinstein.utils.AppConstants;
import com.jeremyfeinstein.utils.NetUtils.ApiResponse;
import com.jeremyfeinstein.utils.NetUtils.JsonCallback;
import com.jeremyfeinstein.utils.NetUtils.SGApiService;
import com.jeremyfeinstein.utils.SPUtil;
import com.nari.ysphd.BuildConfig;
import com.nari.ysphd.R;
import com.nari.ysphd.util.log.WriteHandler;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.CsvFormatStrategy;
import com.orhanobut.logger.DiskLogAdapter;
import com.orhanobut.logger.DiskLogStrategy;
import com.orhanobut.logger.FormatStrategy;
import com.orhanobut.logger.Logger;
import com.orhanobut.logger.PrettyFormatStrategy;

import java.io.File;
import java.text.DecimalFormat;
import java.util.List;

import de.greenrobot.event.EventBus;


public class MainActivity2 extends AppCompatActivity {
    private static final String TAG = "MainActivity2";
    private String Cookie = "CASTGC=TGT-1199-T2VpdFcBf29rqKh7fIbIpCaybJ2zf0ATeNrfOhxRT97AOfM2aF-pi6000-ua-sso; SESSION=0fba8a3d-8e84-40f5-8080-de2608e080b0; _at=eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIwOTE0YTdhZGQxNTYxMWU2ODhjYzU0ZWU3NTM2Y2M1MiIsImlhdCI6MTYxNDA0NjY2NCwic3ViIjoicGlhZG1pbiIsImF1ZCI6InBpYWRtaW4iLCJleHAiOjE2MTQwNDg0NjR9.sXx72IUF1nkESIreT8Voa4rG8ynrefWY9yyPFePlziA; _rt=eyJ0dGwiOjE4MDAsImFsZyI6IkhTMjU2In0.eyJqdGkiOiIwOTE0YTdhZGQxNTYxMWU2ODhjYzU0ZWU3NTM2Y2M1MiIsImlhdCI6MTYxNDA0NjY2NCwic3ViIjoicGlhZG1pbiIsImF1ZCI6InBpYWRtaW4iLCJleHAiOjE2MTQxMzMwNjR9.0Um_4da7gRnnWju1Get2YAyOR1Cm0Zm8xCQ5oz0nAbg";
    private long startTimeMillis;
    private long startBytes;
    private String devCode;
    private String devName;
    private String token;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        //region log
        FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
                .showThreadInfo(false)  // 是否显示线程信息，默认为ture
                .methodCount(3)         // 显示的方法行数，默认为2
//                .methodOffset(1)   // 隐藏内部方法调用到偏移量，默认为5
//                .logStrategy()     // 更改要打印的日志策略。
                .tag("custom tag")   // 每个日志的全局标记。默认PRETTY_LOGGER
                .build();

        Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy) {
            @Override
            public boolean isLoggable(int priority, @Nullable String tag) {
                return BuildConfig.DEBUG;
            }
        });

        //默认保存的路径： /storage/emulated/0
        //Logger.addLogAdapter(new DiskLogAdapter());


        int MAX_BYTES = 500 * 1024; //500K平均4000行一个文件  500K averages to a 4000 lines per file

        //日志保存路径
        String diskPath = Environment.getExternalStorageDirectory().getAbsolutePath();
        String folder = diskPath + File.separatorChar + "logger";

        HandlerThread ht = new HandlerThread("AndroidFileLogger." + folder);
        ht.start();
        Handler handler = new WriteHandler(ht.getLooper(), folder, MAX_BYTES);
        DiskLogStrategy logStrategy = new DiskLogStrategy(handler);


        formatStrategy = CsvFormatStrategy.newBuilder()
                .logStrategy(logStrategy).build();

        Logger.addLogAdapter(new DiskLogAdapter(formatStrategy) {
            @Override
            public boolean isLoggable(int priority, String tag) {
                return BuildConfig.DEBUG;
            }
        });
        //endregion


        devCode = getDevCode();
        devName = getDevName();

        Logger.e(TAG + "devCode =  %s , devName = %s", devCode, devName);
        // devName = Xiaomi HQS8BIDE7LSK6L4S
        // imsi = 863100032945127
        // imsi = f5e75cbda3b09454

        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void onEventMainThread(HDMsgEvent event) {
        Log.e(TAG, "hdmsg: event.url " + event.url);
        Log.e(TAG, "hdmsg: event.MsgType " + event.MsgType);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Logger.e("%s", TAG + " onResume");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Logger.e("%s", TAG + " onStop");
    }

    public void onClick(View view) {

        String ip = (String) SPUtil.get(AppConstants.Platform_IP, "");
        String port = (String) SPUtil.get(AppConstants.Platform_PORT, "");

        Log.e(TAG, "onClick: ip = " + ip + " port = " + port);

        String baseUrl = "http://172.16.219.211:13006/uvp-backend-consultation/api/equipment/";
        String baseUrl1 = "http://172.16.219.211/uvp-backend-consultation/api/equipment/";

        SGApiService.init(baseUrl, null);

        HDMsgEvent event = new HDMsgEvent();
        event.url = baseUrl;
        event.MsgType = HDMsgEvent.Type.start;
        EventBus.getDefault().post(event);


        if (view.getId() == R.id.addDV) {
            SGApiService.postJSON("addDevice")
//                    .addParam("devName", "测试名称10001")
                    .addParam("devName", devName)
                    .addParam("devCode", devCode)
                    .post(getCallback());
        } else if (view.getId() == R.id.updateDevice) {
            SGApiService.postJSON("updateDevice")
                    .addParam("devName", "测试名称10010")
                    .addParam("devCode", "11111111111111")
                    .post(getCallback());
        } else if (view.getId() == R.id.queryDevice) {
            SGApiService.postJSON(baseUrl1 + "queryDevice")
                    .addHeader("token", token)
                    .addParam("devName", devName)
                    .addParam("devStatus", "")
                    .addParam("authorizationStatus", "")
                    .addParam("pageNo", "1")
                    .addParam("pageSize", "10")
                    .post(getCallback());
        } else if (view.getId() == R.id.deleteDevice) {
            SGApiService.postJSON("deleteDevice")
                    .addParam("devCode", devCode)
                    .post(getCallback());
        } else if (view.getId() == R.id.authorizeDevice) {
            SGApiService.postJSON("authorizeDevice")
//                    .addHeader("Cookie", Cookie)
                    .addParam("devCode", devCode)
                    .post(getCallback());
        } else if (view.getId() == R.id.cancelAuthorizeDevice) {
            SGApiService.postJSON("cancelAuthorizeDevice")
                    .addParam("devCode", devCode)
                    .post(getCallback());
        } else if (view.getId() == R.id.queryDeviceDetail) {
            SGApiService.postJSON("queryDeviceDetail")
                    .addParam("devCode", devCode)
                    .post(getCallback());
        } else if (view.getId() == R.id.deviceRunStart) {
            startTimeMillis = System.currentTimeMillis();
            startBytes = getTotalBytes();

            Log.e(TAG, "onClick: startTimeMillis = " + startTimeMillis);
            SGApiService.postJSON("deviceRunStart")
                    .addParam("devCode", devCode)
                    .addParam("serverIp", "172.16.219.211")
                    .post(getCallback());
        } else if (view.getId() == R.id.deviceRunOver) {
            long timeMillis = System.currentTimeMillis() - startTimeMillis;
            Log.e(TAG, "onClick: timeMillis = " + timeMillis);
            long timeS = timeMillis / 1000;
            Log.e(TAG, "onClick: timeS = " + timeS);
            long timeM = timeS / 60;
            Log.e(TAG, "onClick: timeM = " + timeM + "." + timeS % 60);
            long timeH = timeM / 60;
            Log.e(TAG, "onClick: timeH = " + timeH);

            String duration = timeM + "." + timeS % 60;

            long endBytes = getTotalBytes() - startBytes;
            Log.e(TAG, "onClick: endBytes = " + endBytes);
            DecimalFormat format = new DecimalFormat("0.00");
            double i = (endBytes / (1024.0 * 1024.0));
            Log.e(TAG, "onClick: i = " + i);
            String consumeFlow = format.format(i);
            Log.e(TAG, "onClick: consumeFlow = " + consumeFlow);

            SGApiService.postJSON("deviceRunOver")
                    .addParam("devCode", devCode)
                    .addParam("duration", duration)
                    .addParam("consumeFlow", consumeFlow)
                    .post(getCallback());
        } else if (view.getId() == R.id.queryDeviceLog) {
            SGApiService.postJSON("queryDeviceLog")
                    .addParam("devCode", devCode)
                    .addParam("pageNo", "1")
                    .addParam("pageSize", "10")
                    .post(getCallback());
        } else if (view.getId() == R.id.login) {

            byte[] encode = Base64.encode("1qaz2wsx#".getBytes(), Base64.DEFAULT);
            String s = new String(encode);

            String url = "http://172.16.219.211/pi6000-ua-web/api/ua/auth/validateUser";
            SGApiService.postJSON(url)
                    .addParam("username", "piadmin")
                    .addParam("upwd", s)
                    .post(new JsonCallback<LoginBean>() {
                        @Override
                        public void onSuccess(ApiResponse<LoginBean> response) {
                            super.onSuccess(response);
                            Logger.e("Response  %s", "onSuccess: " + response.body);
                            token = response.body.getData().getToken();
                        }

                        @Override
                        public void onError(ApiResponse<LoginBean> response) {
                            super.onError(response);
                            Logger.e("Response  %s", "onError: " + response.message);
                        }
                    });
        } else if (view.getId() == R.id.init) {
            initDevInfo();
        }

    }

    public void initDevInfo() {
        SGApiService.postJSON("queryDevice")
                .addParam("devName", devName)
                .addParam("devStatus", "")
                .addParam("authorizationStatus", "")
                .addParam("pageNo", "1")
                .addParam("pageSize", "10")
                .post(new JsonCallback<QueryDeviceBean>() {
                    @Override
                    public void onSuccess(ApiResponse<QueryDeviceBean> response) {
                        super.onSuccess(response);
                        QueryDeviceBean body = response.body;
                        Log.e(TAG, "onSuccess: body = " + body);
                        if (body.isSuccessful() && "200".equals(body.getResultCode())) {
                            List<QueryDeviceBean.ResultValueBean> resultValue = body.getResultValue();
                            if (resultValue != null && resultValue.size() == 0) {
                                Log.e(TAG, "onSuccess: -----------");
                                SGApiService.postJSON("addDevice")
                                        .addParam("devName", devName)
                                        .addParam("devCode", devCode)
                                        .post(getCallback());
                            }
                        }
                    }

                    @Override
                    public void onError(ApiResponse<QueryDeviceBean> response) {
                        super.onError(response);
                        Log.e(TAG, "onError: response.message " + response.message);
                    }
                });
    }

    private long getTotalBytes() {
        long uidRxBytes = TrafficStats.getUidRxBytes(this.getApplicationInfo().uid);
        long uidTxBytes = TrafficStats.getUidTxBytes(this.getApplicationInfo().uid);
        long startBytes = uidRxBytes + uidTxBytes;
        Log.e(TAG, " uidRxBytes = " + uidRxBytes);
        Log.e(TAG, " uidTxBytes = " + uidTxBytes);
        Log.e(TAG, " startBytes = " + startBytes);
        return startBytes;
    }

    private String getDevCode() {
        TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        String devCode = tm.getDeviceId();

        if (TextUtils.isEmpty(devCode)) {
            devCode = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
        }
        return devCode;
    }

    private String getDevName() {
        String devName;
        try {
            devName = Build.class.getField("SERIAL").get(null).toString();
        } catch (Exception e) {
            devName = e.getMessage().hashCode() + "";
        }

        String brand = Build.BRAND;
        return brand + devName;
    }

    public static String getNetFileSizeDescription(long size) {
        StringBuffer bytes = new StringBuffer();
        DecimalFormat format = new DecimalFormat("###.0");
        if (size >= 1024 * 1024 * 1024) {
            double i = (size / (1024.0 * 1024.0 * 1024.0));
            bytes.append(format.format(i)).append("GB");
        } else if (size >= 1024 * 1024) {
            double i = (size / (1024.0 * 1024.0));
            bytes.append(format.format(i)).append("MB");
        } else if (size >= 1024) {
            double i = (size / (1024.0));
            bytes.append(format.format(i)).append("KB");
        } else if (size < 1024) {
            if (size <= 0) {
                bytes.append("0B");
            } else {
                bytes.append((int) size).append("B");
            }
        }
        return bytes.toString();
    }


//    private JsonCallback<AddDvBean> getCallback() {
//        return new JsonCallback<AddDvBean>() {
//            @Override
//            public void onSuccess(ApiResponse<AddDvBean> response) {
//                super.onSuccess(response);
//                Log.e(TAG, "onSuccess: " + response.body);
//            }
//
//            @Override
//            public void onError(ApiResponse<AddDvBean> response) {
//                super.onError(response);
//                Log.e(TAG, "onError: " + response.message);
//            }
//        };
//    }

//    private JsonCallback<UpdateDVBean> getCallback() {
//        return new JsonCallback<UpdateDVBean>() {
//            @Override
//            public void onSuccess(ApiResponse<UpdateDVBean> response) {
//                super.onSuccess(response);
//                Log.e(TAG, "onSuccess: " + response.body);
//            }
//
//            @Override
//            public void onError(ApiResponse<UpdateDVBean> response) {
//                super.onError(response);
//                Log.e(TAG, "onError: " + response.message);
//            }
//        };
//    }


//    private JsonCallback<QueryDeviceBean> getCallback() {
//        return new JsonCallback<QueryDeviceBean>() {
//            @Override
//            public void onSuccess(ApiResponse<QueryDeviceBean> response) {
//                super.onSuccess(response);
//                Log.e(TAG, "onSuccess: " + response.body);
//            }
//
//            @Override
//            public void onError(ApiResponse<QueryDeviceBean> response) {
//                super.onError(response);
//                Log.e(TAG, "onError: " + response.message);
//            }
//        };
//    }


//    private JsonCallback<DeleteDeviceBean> getCallback() {
//        return new JsonCallback<DeleteDeviceBean>() {
//            @Override
//            public void onSuccess(ApiResponse<DeleteDeviceBean> response) {
//                super.onSuccess(response);
//                Log.e(TAG, "onSuccess: " + response.body);
//            }
//
//            @Override
//            public void onError(ApiResponse<DeleteDeviceBean> response) {
//                super.onError(response);
//                Log.e(TAG, "onError: " + response.message);
//            }
//        };
//    }

//    private JsonCallback<QueryDeviceDetailBean> getCallback() {
//        return new JsonCallback<QueryDeviceDetailBean>() {
//            @Override
//            public void onSuccess(ApiResponse<QueryDeviceDetailBean> response) {
//                super.onSuccess(response);
//                Log.e(TAG, "onSuccess: " + response.body);
//            }
//
//            @Override
//            public void onError(ApiResponse<QueryDeviceDetailBean> response) {
//                super.onError(response);
//                Log.e(TAG, "onError: " + response.message);
//            }
//        };
//    }


    private JsonCallback<String> getCallback() {
        return new JsonCallback<String>() {
            @Override
            public void onSuccess(ApiResponse<String> response) {
                super.onSuccess(response);
                Logger.e("Response  %s", "onSuccess: " + response.body);
            }

            @Override
            public void onError(ApiResponse<String> response) {
                super.onError(response);
                Logger.e("Response  %s", "onError: " + response.message);
            }
        };
    }


}